package com.edu.shiro.controller;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.edu.shiro.mapper.RoleMapper;
import com.edu.shiro.session.ShiroSessionListener;
import com.edu.shiro.shiroconfig.RetryLimitHashedCredentialsMatcher;
import com.edu.shiro.shiroconfig.UserRealm;

@RestController
public class UserController {
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private SecurityManager securityManager;
	
	@Autowired
	private ShiroSessionListener sessionListener;
	
	@GetMapping("/user/unauth")
	public String unauth(){
		return "未授权页面";
	}
	
	@GetMapping("/user/error")
	public String error(){
		return "服务器异常";
	}
	
	@GetMapping("/user/testRole")
	@RequiresRoles("admin")
	public String testRole(){
		return "admin角色才能访问";
	}
	
	@GetMapping("/user/testAuth")
	@RequiresPermissions("system:user:pladd")
	public String testAuth(){
		return "拥有system:user:pladd该权限的可以访问";
	}
	
	
	  /**
     * 给admin用户添加 system:user:pladd 权限
     */
	@GetMapping("/addPermission")
	public String addPermission(Model model){
		roleMapper.insetPermission(1L, 1058L);
		//添加成功，清除缓存
		DefaultWebSecurityManager secuManager = (DefaultWebSecurityManager)securityManager;
		UserRealm userRealm = (UserRealm)secuManager.getRealms().iterator().next();
		//清除权限相关缓存
		userRealm.clearAllCachedAuthorizationInfo();
		return "给用户admin添加system:user:pladd 权限成功";
	}
	
	
	@GetMapping("cleanPermission")
	public String cleanPermission(){
		//添加成功，清除缓存
		DefaultWebSecurityManager secuManager = (DefaultWebSecurityManager)securityManager;
		UserRealm userRealm = (UserRealm)secuManager.getRealms().iterator().next();
		//清除权限相关缓存
		userRealm.clearAllCachedAuthorizationInfo();
		return "清除缓存成功";
	}
	
	@GetMapping("/getcount")
	public String getOnlineConunt(){
		return sessionListener.getSessionCount().toString();
	}
	
	@Autowired
	private RetryLimitHashedCredentialsMatcher reCredentialsMatcher;
	
	/**
	 * 解除admin用户的限制登录
	 */
	@GetMapping("/unlockAcccount")
	public String unlockAcccount(Model model){
		model.addAttribute("msg", "用户解锁成功");
		reCredentialsMatcher.unlockAccount("admin");
		return "loginpage";
	}
}
